<template lang="pug">
.page
  .area-manage
    .search-form.mb-10.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 商保编号：
          Input(v-model="securityNO" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 商保专员：
          Select.input-has-border(v-model="commissionerUserId" label-in-value clearable filterable)
            Option(v-for="item in commissionerUserIdArr" :value="item.key" :key="item.key") {{item.value}}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 是否收款：
          RadioGroup.beautiful-radio-group(type="button" v-model="isReceivables")
            Radio(label="") 全部
            Radio(label="true") 是
            Radio(label="false") 否
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 是否开票：
          RadioGroup.beautiful-radio-group(type="button" v-model="isInvoice")
            Radio(label="") 全部
            Radio(label="true") 是
            Radio(label="false") 否
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 状态：
          RadioGroup.beautiful-radio-group(type="button" v-model="enabled")
            Radio(label="true") 启用
            Radio(label="false") 禁用
          Button.ml-10(v-if="hasFind" type="info" @click="searchBtn") 查询
    .odd-manage.pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="thead" :data="codeListData" @on-selection-change="tableSelectChange")
        .clearfix.font-14(slot="header")
          .table-title-lefttxt.pull-left
            span
              | 商保编号:
              span.text-info.pl-5.pr-5.font-weight {{securityNoCount}}
              | 条
            Divider(type="vertical")
            span
              | 保险公司:
              span.text-info.pl-5.pr-5.font-weight {{companyCount}}
              | 家
          .pull-right.table-title-btns
            Button.mr-15(v-if="hasCreate" size="small" type="info" @click="addFn") 新增
            Button.mr-15(v-if="hasImport" size="small" type="info" @click="importBtn") 批量导入
            Button(v-if="hasExport" size="small" type="info" @click="exportBtn") 导出
            //- Button(v-if="hasDelete" type="warning" @click="cancelFn") 删除
        template(slot-scope="{ row, index }" slot="operation")
          Button.mr-5(v-if="hasView" type="text" size="small" @click="checkInfoFn(row.id)") 查看
          Button(v-if="hasEdit" type="text" size="small" @click="getReviseAfInfo(row.id)") 修改
          Button(v-if="hasDisEnabled && row.enabled" type="text" size="small" @click="getEnabled(row.id,false)") 禁用
          Button(v-if="hasEnabled && !row.enabled" type="text" size="small" @click="getEnabled(row.id,true)") 启用
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
      //- div(style="margin: 10px;overflow: hidden")
      //-   div(style="float: right;")
      //-     Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    include ./modal/add.pug
    include ./modal/check.pug
    BatchImportModal(ref="BatchImportModal" :securityType="securityType" @query="searchBtn" @handleMaxSizeTen="handleMaxSizeTen")

</template>

<script>
// import areaData from '@/libs/areaData.min.js'
import systemApi from '@/api/system.js'
import dataApi from '@/api/data.js'
import codeManageApi from '@/api/codeManage.js'
import BatchImportModal from './modal/BatchImportModal.vue'

export default {
  name: 'ciCodeManage',
  components: {
    BatchImportModal
  },
  data () {
    return {
      isReceivables: '', // 是否收款
      isInvoice: '', // 是否开票
      serviceFormArr: [],
      serviceForm: '', // 服务形式
      add_isReceivables: true, // 新增时是否收款
      add_isInvoice: true, // 新增时是否开票
      commissionerUserId: '',
      add_commissionerUserId: '',
      add_commissionerUserName: '',
      commissionerUserIdArr: [],
      enabled:'true',
      add_enabled: true,

      securityNoCount: 0,
      companyCount: 0,
      // 弹窗加载状态
      spinShow: false,
      // 参保类型（1社会保险、2公积金、3商保）
      securityType: 3,
      // 所有地区
      // areaArr: areaData,
      // 查询-参保地区
      areaName: [],
      // 查询-公积金编号
      securityNO: '',
      // 查询-单位名称
      companyName: '',
      // 方案列表
      codeListData: [],
      // 方案总数
      codeTotal: 0,
      PageIndex: 1,
      PageSize: 10,
      loading: false,
      // table选择的id集合
      idList: [],
      // 收费精度下拉
      precisionSelect: [],
      // 是否可替换
      canReplaceSelect: [
        { value: 'false', label: '否' },
        { value: 'true', label: '是' }
      ],
      // 是否可替换的值
      canReplace: null,
      canReplaceValue: null,
      // 计算方式下拉
      paymentTypeSelect: [
        { value: 'Month', label: '按月收取' },
        { value: 'Year', label: '按年收取' }
      ],
      // 生效时间下拉
      effectiveTime: null,
      // 新增弹窗
      addModalShow: false,
      // 查看修改弹窗
      checkModalShow: false,
      // 查看和修改弹窗的title
      checkModalTitle: '编号查看',
      // 是否处于查看状态
      isCheckModel: false,
      // 编号详情，点击查看和修改时获取
      codeDetailInfo: {},
      // 新增时获取的提交信息集合
      addDetailInfo: {},
      // 查看详情id
      detail_id: '',
      // 查看-参保地区
      dt_area_name: [],

      // 新增--社保编号
      add_securityNO: '',
      // 新增--单位名称
      add_companyName: '',
      // 新增--商保金额
      add_totalAmount: '',
      // 新增--费用收取方式
      add_PaymentType: '',
      // 新增--是否可替换
      add_canReplaceValue: false,
      // 新增--异动操作时长
      add_changeOperateDuration: '',
      // 新增--增员起止时间
      add_increasDay: {
        begin: 1,
        end: 31
      },
      // 新增--减员起止时间
      add_reduceDay: {
        begin: 1,
        end: 31
      },
      // 参保方案下拉选项
      planOptions: [],
      // 新增时参保方案下拉选项
      add_planOptions: [],
      // 新增时参保方案id
      add_planGUID: '',
      add_dis: true,
      thead: [
        {
          type: 'selection',
          align: 'center',
          fixed: 'left',
          width: 60
        },
        {
          title: '商保编号',
          align: 'center',
          tooltip: true,
          minWidth: 150,
          key: 'securityNO'
        },
        {
          title: '保险公司',
          align: 'center',
          tooltip: true,
          minWidth: 150,
          key: 'companyName'
        },
        {
          title: '商保金额',
          align: 'center',
          minWidth: 90,
          key: 'totalAmount'
        },
        {
          title: '费用收取方式',
          align: 'center',
          tooltip: true,
          minWidth: 100,
          key: 'paymentTypeName'
        },
        {
          title: '是否收款',
          align: 'center',
          minWidth: 90,
          render: (h, params) => {
            return h('span', params.row.isReceivables?'是':'否')
          }
        },
        {
          title: '是否开票',
          align: 'center',
          minWidth: 90,
          render: (h, params) => {
            return h('span', params.row.isInvoice?'是':'否')
          }
        },
        {
          title: '商保专员',
          align: 'center',
          minWidth: 90,
          key: 'commissionerUserName'
        },
        {
          title: '状态',
          align: 'center',
          minWidth: 190,
          key: 'enabled',
          render: (h, params) => {
            let row = params.row
            return h('span', row.enabled?'启用':'禁用')
          }
        },
        {
          title: '添加时间',
          align: 'center',
          minWidth: 190,
          key: 'createdOn',
          render: (h, params) => {
            let row = params.row
            let times = row.createdOn.slice(0, 19).replace(/T/g, ' ')
            return h('span', times)
          }
        },
        {
          title: '添加人',
          align: 'center',
          minWidth: 100,
          key: 'createdName'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          slot: 'operation',
          fixed: 'right',
          minWidth: 220
        }
      ],
      // 增员生效时间值
      addEffectiveValue: '',
      // 减员生效时间值
      reduceEffectiveValue: '',
      // 截止时间
      endTime: [{ value: 1, label: '1号' }, { value: 2, label: '2号' }, { value: 3, label: '3号' }, { value: 4, label: '4号' }, { value: 5, label: '5号' }, { value: 6, label: '6号' }, { value: 7, label: '7号' }, { value: 8, label: '8号' }, { value: 9, label: '9号' }, { value: 10, label: '10号' }, { value: 11, label: '11号' }, { value: 12, label: '12号' }, { value: 13, label: '13号' }, { value: 14, label: '14号' }, { value: 15, label: '15号' }, { value: 16, label: '16号' }, { value: 17, label: '17号' }, { value: 18, label: '18号' }, { value: 19, label: '19号' }, { value: 20, label: '20号' }, { value: 21, label: '21号' }, { value: 22, label: '22号' }, { value: 23, label: '23号' }, { value: 24, label: '24号' }, { value: 25, label: '25号' }, { value: 26, label: '26号' }, { value: 27, label: '27号' }, { value: 28, label: '28号' }, { value: 29, label: '29号' }, { value: 30, label: '30号' }, { value: 31, label: '31号' }]
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 新增
    hasCreate () {
      return this.actionArr.indexOf('Create') > -1
    },
    // 查看
    hasView () {
      return this.actionArr.indexOf('View') > -1
    },
    // 编辑
    hasEdit () {
      return this.actionArr.indexOf('Edit') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 删除
    hasDelete () {
      return this.actionArr.indexOf('Delete') > -1
    },
    // 批量导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 启用
    hasEnabled () {
      return this.actionArr.indexOf('Enabled') > -1
    },
    // 禁用
    hasDisEnabled () {
      return this.actionArr.indexOf('DisEnabled') > -1
    }
  },
  mounted () {
    console.log('mounted-getCICodeList')
    this.getCICodeList()
    this.getEnum()
  },
  methods: {
    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },
    importBtn () {
      this.$refs.BatchImportModal.openModal()
    },
    // 导出
    exportBtn () {
      // if (this.selectedId) {
      codeManageApi.exportCode({
        IdList: this.selectedId,
        areaGUID: this.areaName[this.areaName.length - 1],
        SecurityNO: this.securityNO,
        CompanyName: this.companyName,
        SecurityType: this.securityType
      }).then(res => {
        if (res.data.success) {
          let objectUrl = '/' + res.data.data.replace(/\\/g, '\/')
          console.log(objectUrl)
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    getEnabled(id,status){
      codeManageApi.EnabledCommercial({
        Ids:id,
        Type: this.securityType,
        Enabled:status,
      }).then(res => {
        if (res.data.success) {
          this.getCICodeList()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    /**
     * 分页页码变动
     */
    onpageSizeChange (val) {
      this.PageIndex = 1
      this.PageSize = val
      this.getCICodeList()
    },
    // 获取编号列表
    async getCICodeList () {
      this.loading = true
      let res = await codeManageApi.getCICodeList({
        SecurityNO: this.securityNO,
        SecurityType: this.securityType,
        IsReceivables: this.isReceivables,
        IsInvoice: this.isInvoice,
        CommissionerUserId: this.commissionerUserId,
        Enabled: this.enabled,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      })
      this.idList = []
      this.codeListData = res.data.data
      this.codeTotal = res.data.totalRows
      this.securityNoCount = res.data.securityNoCount
      this.companyCount = res.data.companyCount
      this.loading = false
    },
    // 删除编号
    async deleteCode () {
      let res = await codeManageApi.deleteCICode({
        id: this.idList.join(',')
      })
      if (res.data.success) {
        this.$Message.success('删除成功！！')
        this.idList = []
        this.getCICodeList()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    // 导出
    exportBtn () {
      codeManageApi.exportCommercialCode({
        idList: this.idList,
        SecurityNO: this.securityNO,
        SecurityType: this.securityType,
        IsReceivables: this.isReceivables,
        IsInvoice: this.isInvoice,
        CommissionerUserId: this.commissionerUserId,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      }).then(res => {
        let fileName = '商保编号.xls'
        let blob = new Blob([res.data], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          let objectUrl = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = fileName
          link.href = objectUrl
          link.click()
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    // 获取下拉
    async getEnum () {
      let groupNames = 'common.precision,common.reduceeffecttype,common.totaltype,common.changeoperateduration,user.supplierlist'
      let res = await dataApi.getEnum({
        groupName: groupNames
      })
      this.precisionSelect = this.getItems(res.data, 'common.precision')
      this.countType = this.getItems(res.data, 'common.totaltype')
      this.effectiveTime = this.getItems(res.data, 'common.reduceeffecttype')
      this.commissionerUserIdArr = this.getItems(res.data, 'user.supplierlist')
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },
    // 获取查看时的详情信息
    async getCodeDetail () {
      this.spinShow = true
      let res = await codeManageApi.getCICodeDetail({
        id: this.detail_id
      })
      this.codeDetailInfo = res.data.data
      this.spinShow = false
    },
    detailCommissionerUserIdChange (val) {
      if (val) {
        this.codeDetailInfo.commissionerUserName = val.label
      } else {
        this.codeDetailInfo.commissionerUserName = ''
      }
    },
    // 保存修改
    async saveRevise () {
      let res = await codeManageApi.saveReviseCICode({
        IsReceivables: this.codeDetailInfo.isReceivables,
        IsInvoice: this.codeDetailInfo.isInvoice,
        CommissionerUserId: this.codeDetailInfo.commissionerUserId,
        CommissionerUserName: this.codeDetailInfo.commissionerUserName,
        Enabled: this.codeDetailInfo.enabled,

        Id: this.codeDetailInfo.id,
        SecurityType: this.securityType,
        SecurityNO: this.codeDetailInfo.securityNO,
        CompanyName: this.codeDetailInfo.companyName,
        TotalAmount: this.codeDetailInfo.totalAmount,
        PaymentType: this.codeDetailInfo.paymentType,
        CanReplace: this.codeDetailInfo.canReplace,
        IncreasDay: this.codeDetailInfo.increasDay,
        ReduceDay: this.codeDetailInfo.reduceDay,
        ChangeOperateDuration: this.codeDetailInfo.changeOperateDuration
      })
      if (res.data.success) {
        this.$Message.success('修改成功！')
        this.isCheckModel = true
        this.checkModalTitle = '编号查看'
        this.getCICodeList()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    addCommissionerUserIdChange (val) {
      if (val) {
        this.add_commissionerUserName = val.label
      } else {
        this.add_commissionerUserName = ''
      }
    },
    // 确定新增
    async addSave () {
      if (this.add_totalAmount === '') {
        this.$Message.error('商保金额不能为空')
        return false
      }
      if (this.add_companyName === '') {
        this.$Message.error('保险公司不能为空')
        return false
      }
      let res = await codeManageApi.saveReviseCICode({
        IsReceivables: this.add_isReceivables,
        IsInvoice: this.add_isInvoice,
        CommissionerUserId: this.add_commissionerUserId,
        CommissionerUserName: this.add_commissionerUserName,
        Enable: this.add_enabled,

        SecurityType: this.securityType,
        SecurityNO: this.add_securityNO,
        CompanyName: this.add_companyName,
        TotalAmount: this.add_totalAmount,
        PaymentType: this.add_PaymentType,
        CanReplace: this.add_canReplaceValue,
        IncreasDay: this.add_increasDay,
        ReduceDay: this.add_reduceDay,
        ChangeOperateDuration: this.add_changeOperateDuration
      })
      if (res.data.success) {
        this.$Message.success('保存成功！')
        this.addModalShow = false
        this.getCICodeList()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
        this.addModalShow = true
      }
    },
    // 计算个人缴纳金额
    async totalMoneyEmployee (data) {
      let res = await systemApi.getTotalAmount({
        Money: data.employee.baseAmount,
        Precision: data.precision,
        Percent: data.employee.percent
      })
      data.employee.totalAmount = res.data.data
    },
    // 计算单位缴纳金额
    async totalMoneyCompany (data) {
      let res = await systemApi.getTotalAmount({
        Money: data.company.baseAmount,
        Precision: data.precision,
        Percent: data.company.percent
      })
      data.company.totalAmount = res.data.data
    },
    // 查询
    searchBtn () {
      this.PageIndex = 1
      this.getCICodeList()
    },
    // 分页
    pageChangeFn (index) {
      this.PageIndex = index
      this.getCICodeList()
    },
    // table选择
    tableSelectChange (value) {
      this.idList = value.map((item) => {
        return item.id
      })
    },
    // 删除按钮
    cancelFn () {
      if (this.idList.length > 0) {
        this.$Modal.confirm({
          title: '确定删除？',
          content: '<p>确认后选择的商保编号将被删除！</p>',
          onOk: () => {
            this.deleteCode()
          },
          onCancel: () => {

          }
        })
      } else {
        this.$Message.warning('请先选择需要删除的编号！')
      }
    },
    // 新增
    addFn () {
      this.addModalShow = true
      this.add_securityNO = ''
      this.add_companyName = ''
      this.add_enabled = true
      // 新增--商保金额
      this.add_totalAmount = ''
      // 新增--费用收取方式
      this.add_PaymentType = ''
      // 新增--是否可替换
      this.add_canReplace = null
      // 新增--异动操作时长
      this.add_changeOperateDuration = ''
      // 新增--增员起止时间
      this.add_increasDay = {
        begin: 1,
        end: 31
      }
      // 新增--减员起止时间
      this.add_reduceDay = {
        begin: 1,
        end: 31
      }
    },
    // 查看
    checkInfoFn (id) {
      this.detail_id = id
      this.checkModalTitle = '编号查看'
      this.isCheckModel = true
      this.checkModalShow = true
      this.getCodeDetail()
    },
    // 修改按钮
    getReviseAfInfo (id) {
      this.detail_id = id
      this.isCheckModel = false
      this.checkModalTitle = '编号修改'
      this.getCodeDetail()
      this.checkModalShow = true
    },
    // 查看弹窗中的关闭
    closeCheckModal () {
      this.checkModalShow = false
    },
    // 查看弹窗中的修改按钮
    reviseFromModal () {
      this.checkModalTitle = '编号修改'
      this.isCheckModel = false
    },
    // 查看修改弹窗中的确认修改按钮
    confirmRevise () {
      this.saveRevise()
    },
    // 新增弹窗中的确定
    confirmFn () {
      this.addSave()
    },
    // 修改是否可替换
    canReplaceChange (val) {
      if (val) {
        this.canReplaceValue = true
      } else {
        this.canReplaceValue = false
      }
    },
    // 新增是否可替换
    // add_canReplaceChange (val) {
    //   if (val) {
    //     this.add_canReplaceValue = true
    //   } else {
    //     this.add_canReplaceValue = false
    //   }
    // },

    // 增员起止时间校验
    increasDayVerification (data) {
      if (data.end < data.begin) {
        this.$Message.warning('截止时间不能早于开始时间！！')
        data.end = data.begin
      }
    },
    // 减员起止时间校验
    reduceDayVerification (data) {
      if (data.end < data.begin) {
        this.$Message.warning('截止时间不能早于开始时间！！')
        data.end = data.begin
      }
    }

  }
}
</script>
<style lang="less">
  .af-add-modal-lzw{
    .ivu-modal-wrap{
      top:10%;
      bottom: 10%;
      left: 10%;
      right: 10%;
    }
    .ivu-input[disabled]{
      color: #333;
    }
    .ivu-select-input[disabled]{
      color: #333;
      -webkit-text-fill-color: #333;
    }
    .ivu-checkbox-disabled.ivu-checkbox-checked .ivu-checkbox-inner:after{
      border-color: #333;
    }
    .ivu-select-disabled .ivu-select-selection{
      color: #333;
    }
  }
</style>
<style lang="less" scoped>
  .search-form-lzw{
    .ivu-col{
      display: flex;
      align-items: center;
      span.label-txt{
        vertical-align: middle;
        float: left;
        min-width: 80px;
        font-size: 12px;
        color: #515a6e;
        line-height: 1;
        padding: 10px 12px 10px 0;
        box-sizing: border-box;
      }
      .ivu-select{
        flex: 1;
      }
      .ivu-input-wrapper{
        flex: 1;
      }
    }
  }
  span.red{
    color: #f00;
  }
</style>
